package ee.sedelitarkvara.util;

/**
 * Sedeliprintimise tarkvara Innovative Millenniumile.
 * 
 * @author	- Indrek Ruubel
 * @date	- 21.02.2012
 * @mail	- indrekruubel@gmail.com 
 *
 */


public class Receipt {
	
	private Settings settings;
	private LabelPrinter labelPrinter;
	private Logger logger;
	
	public Receipt(){
		
		/**
		 * Main procedure
		 */
		
		// Set settings.
		settings = new Settings();
		settings.readIni("settings.ini");
		
		// Start logging to file
		logger = new Logger(settings.getLogging());
		logger.log("Program started.");
		
		// Server infinite loop
		while(true){
			
			// Wait for connection
			PortScanner ps = new PortScanner(settings, logger);
			
			// Wait for it...
			try {
			    ps.t.join();
			}catch (InterruptedException e) {
				System.out.println("Main thread Interrupted");
			}
			// Connection established and data received, moving right along.
			
			// Presumably everything's caught from the port, so we can
			// send it to printing.
			labelPrinter = new LabelPrinter();
			
			// First check, never gonna be null though...
			if(ps.getHandler() != null){
				try{
					// Last filter checking a variable.
					if(ps.getHandler().getReader() != "undefined"){
						logger.log("Printing "+ps.getHandler().getBooks().size()+" book(s) to "+ps.getHandler().getReader());
						if(ps.getHandler().getBooks().size() == 0){
							logger.log("0 books to "+ps.getHandler().getReader()+", no point in printing...");
						}else{
							labelPrinter.printPrinterJob(ps.getHandler(), settings);
						}
					}
				}catch(Exception ex){
					System.out.println("Error: "+ex);
				}
				logger.log("All printing done, back to port listening.");
			}
		}
	}
}
